package com.zdlog.wenjuan.service;

import com.zdlog.wenjuan.constant.CookieConstant;
import com.zdlog.wenjuan.constant.RedisConstant;
import com.zdlog.wenjuan.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by 廖师兄
 * 2017-07-30 23:19
 */
@Component
@ServerEndpoint("/webSocket/{token}")
@Slf4j
public class WebSocket {

    private Session session;
   // @Autowired
  //  private StringRedisTemplate redisTemplate;

    private static ConcurrentHashMap<String,WebSocket> webSocketSet = new ConcurrentHashMap<String,WebSocket>();
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String userId) {
        this.session = session;
        log.error(userId);
        webSocketSet.put(userId,this);
        log.info("【websocket消息】有新的连接, 总数:{}", webSocketSet.size());
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("【websocket消息】收到客户端发来的消息:{}", message);
    }

    public void sendMessage(String message,String userId) {
        try {
        if (webSocketSet.get(userId) != null) {
            webSocketSet.get(userId).session.getBasicRemote().sendText(message);
        } else {
            log.error("用户未连接");
        }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
